﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace AspectsSample.Helpers
{
    internal static class SerialisationHelper
    {
        internal static bool Serialise<T>(T value, ref string serialisedXml)
        {
            if (value == null)
                return false;

            XmlSerializer xmlserializer = new XmlSerializer(typeof(T));

            StringWriter stringWriter = new StringWriter();

            XmlWriter writer = XmlWriter.Create(stringWriter);

            xmlserializer.Serialize(writer, value);

            serialisedXml = stringWriter.ToString();

            writer.Close();

            return true;
        }

        internal static bool DeserialiseStream<T>(string path, ref T result)
        {
            if (string.IsNullOrWhiteSpace(path))
                return false;

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            StreamReader reader = new StreamReader(path);

            result = (T)serializer.Deserialize(reader);

            reader.Close();

            return true;
        }

        internal static bool Deserialise<T>(string xml, ref T result)
        {
            if (string.IsNullOrWhiteSpace(xml))
                return false;

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            StringReader reader = new StringReader(xml);

            result = (T)serializer.Deserialize(reader);

            reader.Close();

            return true;
        }
    }
}
